﻿using Eyskens.AutoTaggerWeb.Helpers;
using Eyskens.AutoTaggerWeb.Models;
using Eyskens.Spotlight;
using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Eyskens.AutoTaggerWeb.Controllers
{
    public class ExtractInfoSpotlightController : Controller
    {
        // GET: ExtractInfoSpotlight
        public ActionResult Index()
        {
            SpotlightResponseModel model = new SpotlightResponseModel();
            var TokenList = new List<TokenInfo>();
            var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);            
            using (var ctx = spContext.CreateUserClientContextForSPHost())
            {
                LogHelper.Log("ctx is null " + (ctx == null));
                ListItem DocumentItem = null;
                string FileContent = FileHelper.GetFileContent(
                    ctx,
                    new Guid(HttpContext.Request.QueryString["SPListId"]),
                    Convert.ToInt32(HttpContext.Request.QueryString["SPListItemId"]),
                    out DocumentItem);

                Dictionary<string, int> tokens = AutoTaggingHelper.Tokenize(FileContent);
                var SortedTokens = tokens.OrderByDescending(x => x.Value);

                foreach (var token in SortedTokens)
                {
                    TokenList.Add(new TokenInfo
                    {
                        word = token.Key.Replace("\r\n", "").Replace("\n", ""),
                        count=token.Value
                    });
                }
                AppWebHelper hlp = new AppWebHelper(HttpContext.Request.QueryString[Constants.SPAppWebUrl] as string);

                model.tokens = (from word in TokenList
                        where word.word.Length >= 3                        
                        orderby word.count descending
                        select word).Take(50).Where(w=>!AutoTaggingHelper.IsEmptyWord(
                            w.word.ToLowerInvariant(), AutoTaggingHelper.LanguageIdentifier.Identify(FileContent).FirstOrDefault().Item1.Iso639_3, hlp)).Take(10);               
                
                
                SpotlightRequestConfig cfg = new SpotlightRequestConfig(FileContent, "http://spotlight.sztaki.hu:2222/rest/");
                cfg.support = 1;
                cfg.confidence = 0.6;
                try
                {
                    model.annotations = NlpHelper.GetNamedEntitiesforText(cfg);               
                }
                catch(Exception ex)
                {
                    LogHelper.Log(ex.Message + ex.StackTrace);
                    model.ProcessStatus = "Unable to process the analysis with Spotlight. Contact your administrator!";
                }
            }   
            
            
            return View(model);
        }
    }
}